package weatherstation;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import utilities.ANSI;

/**
 * The Class WeatherStation.
 * 
 * @author Nils Berlijn
 * @author Henderikus Harms
 * @version 1.0
 * @since June 1, 2014
 */
public class WeatherStationListener implements Runnable
{
	
	/** The weather station listener socket. */
	private ServerSocket weatherStationListenerSocket;
	
	/** The weather station queue. */
	private WeatherStationQueue<Runnable> weatherStationQueue;		
	
	/** The listen. */
	private boolean listen;
	
	/** The weather station connection. */
	private Socket weatherStationConnection;

	/**
	 * Instantiates a new weather station listener.
	 *
	 * @param port the port
	 * @param WeatherStationQueue the weather station queue
	 */
	public WeatherStationListener(int port, WeatherStationQueue<Runnable> WeatherStationQueue)
	{
		try 
		{
			this.weatherStationListenerSocket = new ServerSocket(port);
			
			System.out.println(ANSI.GREEN + "Weather Station Listener is successfully launched." + ANSI.NORMAL);
			
			this.weatherStationQueue = WeatherStationQueue;
			this.listen = true;				
			
			System.out.println(ANSI.YELLOW + "Weather Station Listener is waiting for incoming connections...\n" + ANSI.NORMAL);
		} 
		catch(IOException e) 
		{
			this.listen = false;
						
			System.out.println(ANSI.RED + "Weather Station Listener is not successfully launched!\n" + ANSI.NORMAL);
		}
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run()
	{	
		while(listen == true)
		{		
			try 
			{
				weatherStationConnection = weatherStationListenerSocket.accept();
				
				System.out.println(ANSI.BLUE + "Weather Station Listener: " + ANSI.GREEN + "\"" + weatherStationConnection.getInetAddress() + "\" has established a new connection" + ANSI.NORMAL);

				try 
				{
					weatherStationQueue.add(new WeatherStationWorker(weatherStationConnection));
					
					System.out.println(ANSI.BLUE + "Weather Station Listener: " + ANSI.YELLOW + "\"" + weatherStationConnection.getInetAddress() + "\" has been added to the queue" + ANSI.NORMAL);	
				} 
				catch(InterruptedException e) 
				{
					System.out.println(ANSI.BLUE + "Weather Station Listener: " + ANSI.RED + "\"" + weatherStationConnection.getInetAddress() + "\" has not been added to the queue" + ANSI.NORMAL);	
				}
			} 
			catch(IOException e) 
			{
				System.out.println(ANSI.RED + "Weather Station Listener: " + ANSI.RED + " Someone has failed by trying too establishing a new connection" + ANSI.NORMAL);
			}			
		}
	}
}